<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title}">泸州市实验小学城西学校资源分享平台</title>
    <link th:href="@{/css/bootstrap.css}" rel="stylesheet">
    <link rel="shortcut icon" th:href="@{../ico/favicon.ico}"/>
    <!-- Font Awesome 图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&family=Noto+Serif+SC:wght@400;600&display=swap"
          rel="stylesheet">
    <!-- Animate.css -->
    <link rel="stylesheet" th:href="@{css/animate.css}">

    <style>
        :root {
            --primary-color: #1e88e5;
            --primary-light: #6ab7ff;
            --primary-dark: #005cb2;
            --secondary-color: #ff9800;
            --accent-color: #f44336;
            --light-bg: #f5f7fa;
            --dark-text: #263238;
            --light-text: #eceff1;
            --gray-text: #607d8b;
            --border-radius: 12px;
            --box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            --box-shadow-hover: 0 8px 30px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }

        body {
            font-family: 'Noto Sans SC', sans-serif;
            background-color: var(--light-bg);
            color: var(--dark-text);
            line-height: 1.6;
            padding-bottom: 50px;
        }

        /* 导航栏样式 */
        .navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            padding: 15px 0;
            transition: var(--transition);
        }

        .navbar.scrolled {
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand {
            font-weight: 700;
            font-size: 1.8rem;
            color: var(--primary-dark) !important;
            display: flex;
            align-items: center;
            font-family: 'Noto Serif SC', serif;
        }

        .navbar-brand i {
            margin-right: 10px;
            font-size: 1.5rem;
            color: var(--secondary-color);
        }

        /* 搜索框样式优化 */
        .search-container {
            position: relative;
            width: 100%;
            max-width: 400px;
        }

        .search-input {
            border-radius: 50px;
            padding-left: 45px;
            border: 1px solid #e0e0e0;
            background-color: white;
            color: var(--dark-text);
            height: 45px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            transition: var(--transition);
        }

        .search-input:focus {
            border-color: var(--primary-light);
            box-shadow: 0 4px 12px rgba(30, 136, 229, 0.2);
            outline: none;
        }

        .search-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-text);
            z-index: 10;
        }

        .search-btn {
            border-radius: 50px;
            padding: 0 20px;
            height: 45px;
            background-color: var(--primary-color);
            border: none;
            transition: var(--transition);
        }

        .search-btn:hover {
            background-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(30, 136, 229, 0.3);
        }

        /* 分类导航侧边栏 */
        .categoryLevel2-sidebar {
            position: sticky;
            top: 100px;
            height: calc(100vh - 120px);
            overflow-y: auto;
            padding-right: 15px;
            scrollbar-width: thin;
            background-color: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
        }

        .categoryLevel2-sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .categoryLevel2-sidebar::-webkit-scrollbar-thumb {
            background-color: rgba(0, 0, 0, 0.2);
            border-radius: 3px;
        }

        .categoryLevel2-header {
            font-weight: 600;
            font-size: 1.1rem;
            color: var(--primary-dark);
            padding: 10px 15px;
            margin-bottom: 10px;
            border-left: 4px solid var(--primary-color);
            background-color: rgba(30, 136, 229, 0.05);
        }

        .categoryLevel2-item {
            padding: 10px 15px;
            margin-bottom: 8px;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
            position: relative;
            display: block;
            color: var(--dark-text);
            text-decoration: none;
        }

        .categoryLevel2-item:hover {
            background-color: rgba(30, 136, 229, 0.1);
            color: var(--primary-dark);
        }

        .categoryLevel2-item.active {
            background-color: rgba(30, 136, 229, 0.15);
            font-weight: 500;
            color: var(--primary-dark);
        }

        .categoryLevel2-item.active::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 3px;
            background-color: var(--primary-color);
            border-radius: 0 3px 3px 0;
        }

        /* 一级分类项样式 */
        .categoryLevel1-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .categoryLevel1-item .toggle-icon {
            transition: var(--transition);
            font-size: 0.9rem;
            color: var(--gray-text);
        }

        .categoryLevel1-item.expanded .toggle-icon {
            transform: rotate(90deg);
        }

        /* 二级分类容器 */
        .level2-container {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }

        .level2-container.expanded {
            max-height: 1000px; /* 足够大的值以容纳所有二级分类 */
        }

        /* 主要内容区域 */
        .main-container {
            padding: 30px 0;
        }

        .page-header {
            margin-bottom: 30px;
            position: relative;
        }

        .categoryLevel2-title {
            font-size: 2rem;
            font-weight: 600;
            color: var(--primary-dark);
            margin-bottom: 15px;
            font-family: 'Noto Serif SC', serif;
            position: relative;
            display: inline-block;
        }

        .categoryLevel2-title::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 60px;
            height: 3px;
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            border-radius: 3px;
        }

        /* 优化文件卡片封面样式 - 适配小尺寸图片 */
        .file-card {
            border: none;
            border-radius: var(--border-radius);
            overflow: hidden;
            transition: var(--transition);
            box-shadow: var(--box-shadow);
            margin-bottom: 25px;
            background-color: white;
            position: relative;
            height: 90%;
            display: flex;
            flex-direction: column;
            cursor: pointer;
            margin-top: 20px; /* 整个卡片上方留白，与上方内容保持间距 */
        }

        .file-thumbnail {
            position: relative;
            overflow: hidden;
            height: 120px;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .file-thumbnail img {
            width: auto;
            height: auto;
            max-width: 80px;
            max-height: 80px;
            object-fit: contain;
            transition: transform 0.5s ease;
            filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
        }

        .file-card:hover .file-thumbnail img {
            transform: scale(1.1);
        }

        .file-info {
            padding: 15px 12px 12px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .file-title {
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--dark-text);
            font-size: 0.95rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            line-height: 1.3;
        }

        .file-description {
            font-size: 0.8rem;
            color: var(--gray-text);
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
            margin-bottom: 0;
            flex-grow: 1;
        }

        .file-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #f0f0f0;
            font-size: 0.7rem;
            color: var(--gray-text);
        }

        .file-type-badge {
            background: var(--primary-light);
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-weight: 500;
        }

        /* 无结果提示 */
        .no-results {
            text-align: center;
            padding: 50px 0;
            color: var(--gray-text);
        }

        .no-results i {
            font-size: 3rem;
            color: var(--primary-light);
            margin-bottom: 20px;
        }

        /* 文件全名提示框样式 */
        .software-tooltip {
            position: absolute;
            z-index: 100;
            background-color: rgba(33, 37, 41, 0.9);
            color: white;
            padding: 0.5rem 0.8rem;
            border-radius: 6px;
            font-size: 0.85rem;
            white-space: nowrap;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .software-tooltip::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 50%;
            transform: translateX(-50%);
            border-width: 5px 5px 0;
            border-style: solid;
            border-color: rgba(33, 37, 41, 0.9) transparent transparent;
        }

        /* 右键菜单样式 */
        .context-menu {
            display: none;
            position: absolute;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            padding: 0.5rem 0;
            min-width: 160px;
            border: 1px solid #f0f0f0;
            transition: var(--transition);
        }

        .context-menu-item {
            padding: 0.6rem 1.2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: var(--transition);
            font-size: 0.9rem;
        }

        .context-menu-item:hover {
            background-color: #f0f5ff;
            color: var(--primary-color);
            padding-left: 1.3rem;
        }

        .context-menu-item i {
            margin-right: 0.6rem;
            font-size: 0.95rem;
            width: 18px;
            text-align: center;
        }

        /* 模态框样式 */
        .modal-content {
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            border: none;
            animation: modalFadeIn 0.3s ease;
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 1rem 1.5rem;
        }

        .modal-title {
            font-weight: 600;
            font-size: 1.1rem;
        }

        .modal-body {
            padding: 1.5rem;
        }

        .modal-footer {
            padding: 1rem 1.5rem;
            border-top: 1px solid #f0f0f0;
        }

        .badge {
            padding: 0.4rem 0.6rem;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            transition: var(--transition);
            border-radius: 50px;
        }

        .btn-primary:hover {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(30, 136, 229, 0.3);
        }

        .btn-secondary {
            border-radius: 50px;
        }

        /* 响应式调整 */
        @media (max-width: 1199.98px) {
            .categoryLevel2-sidebar {
                height: auto;
                max-height: 400px;
                margin-bottom: 30px;
                position: static;
            }
        }

        @media (max-width: 991.98px) {
            .navbar-brand {
                font-size: 1.5rem;
            }

            .categoryLevel2-title {
                font-size: 1.8rem;
            }

            .search-container {
                max-width: 300px;
            }
        }

        @media (max-width: 767.98px) {
            .categoryLevel2-title {
                font-size: 1.6rem;
            }

            .file-card {
                margin-bottom: 20px;
            }

            .navbar-collapse {
                margin-top: 15px;
            }

            .search-container {
                max-width: 100%;
            }
        }

        @media (max-width: 575.98px) {
            .navbar-brand {
                font-size: 1.3rem;
            }

            .categoryLevel2-title {
                font-size: 1.4rem;
            }

            .search-btn {
                padding: 0 15px;
            }
        }

        /* 动画效果 */
        .animate-fade-in {
            animation: fadeIn 0.6s ease forwards;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .file-card {
            opacity: 0;
        }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<nav class="navbar navbar-expand-lg navbar-light sticky-top">
    <div class="container">
        <a class="navbar-brand" href="#">
            <i class="fas fa-share-alt"></i>
            <span th:text="${title}">泸州市实验小学城西学校资源分享平台</span>
        </a>

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarContent">
            <form id="searchForm" class="d-flex ms-auto search-container">
                <i class="fas fa-search search-icon"></i>
                <input class="form-control search-input" type="search"
                       placeholder="搜索资源..." aria-label="Search"
                       id="searchInput" th:value="${currentQuery != null ? currentQuery : ''}">
                <button class="btn btn-primary ms-2 search-btn" type="submit">
                    <i class="fas fa-search"></i>
                </button>
            </form>
        </div>
    </div>
</nav>
<!-- 主要内容区域 -->
<div class="main-container">
    <div class="container">
        <div class="row">
            <!-- 左侧：一级分类侧边栏 -->
            <div class="col-lg-3">
                <div class="categoryLevel2-sidebar p-4">
                    <h5 class="categoryLevel2-header">资源分类</h5>
                    <div id="categoryTree">
                        <!-- 全部资源 -->
                        <a th:href="@{?}" class="categoryLevel2-item"
                           th:classappend="${currentLevel1Id == null and currentLevel2Id == null and currentQuery == null} ? 'active'">
                            <i class="fas fa-th-large me-2"></i>
                            <span>全部资源</span>
                        </a>

                        <!-- 一级分类循环 -->
                        <div th:each="level1 : ${level1Categories}">
                            <!-- 一级分类标题（可点开显示二级） -->
                            <a href="#"
                               class="categoryLevel2-item categoryLevel1-item d-flex justify-content-between align-items-center"
                               th:classappend="${level1.id == currentLevel1Id and currentLevel2Id == null} ? 'active'"
                               th:attr="data-level1-id=${level1.id}">
                                <span>
                                    <i class="fas fa-folder me-2"></i>
                                    <span th:text="${level1.name}">一级分类名称</span>
                                </span>
                                <small class="toggle-icon">
                                    <i class="fas fa-chevron-right"></i>
                                </small>
                            </a>

                            <!-- 二级分类列表（嵌套） -->
                            <div class="level2-container ms-3"
                                 th:if="${level1.level2Categories != null and !level1.level2Categories.isEmpty()}">
                                <a th:each="level2 : ${level1.level2Categories}"
                                   class="categoryLevel2-item categoryLevel2-item-nested"
                                   th:classappend="${level2.id == currentLevel2Id} ? 'active'"
                                   th:attr="data-level1-id=${level1.id},data-level2-id=${level2.id}">
                                    <i class="fas fa-folder-open me-2"></i>
                                    <span th:text="${level2.name}">二级分类名称</span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：文件内容区域 -->
            <div class="col-lg-9">
                <!-- 上侧：当前分类标题 -->
                <div class="page-header">
                    <h1 class="categoryLevel2-title" th:text="${currentCategoryName}">
                        全部资源
                    </h1>
                </div>

                <!-- 下侧：文件卡片容器 -->
                <div class="row" id="fileCardsContainer">
                    <!-- 文件卡片循环 -->
                    <div class="col-xl-3 col-lg-4 col-md-6" th:each="file : ${currentFiles}">
                        <div class="file-card animate-fade-in"
                             th:attr="data-id=${file.id}, data-uuid-name=${file.storageName}, data-name=${file.originalName}, data-size=${file.fileSize}, data-type=${file.fileType}">
                            <!-- 文件封面 -->
                            <div class="file-thumbnail">
                                <img th:src="|/images/file-icons/${file.fileType}.png|"
                                     th:onerror="|this.src='/images/file-icons/default.png'|"
                                     loading="lazy">
                            </div>

                            <!-- 文件信息（名称+介绍） -->
                            <div class="file-info">
                                <h5 class="file-title" th:text="${file.originalName}">文件名称</h5>
                                <p class="file-description"
                                   th:text="${#strings.isEmpty(file.fileDescription)} ? '该资源暂无详细介绍，右键点击可下载或预览' : ${file.fileDescription}">
                                    该资源暂无详细介绍，右键点击可下载或预览
                                </p>
                                <div class="file-meta">
                                    <span class="file-type-badge" th:text="${file.fileType.toUpperCase()}">FILE</span>
                                    <span class="file-size" th:attr="data-size=${file.fileSize}">0 MB</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 无结果提示 -->
                    <div class="col-12" th:if="${currentFiles == null or currentFiles.isEmpty()}">
                        <div class="no-results">
                            <i class="fas fa-file-alt"></i>
                            <h4>暂无相关资源</h4>
                            <p th:if="${currentQuery != null}">
                                没有找到与"[[${currentQuery}]]"相关的资源，请尝试其他关键词
                            </p>
                            <p th:if="${currentQuery == null}">
                                当前分类下还没有资源内容，请尝试其他分类
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 右键菜单 -->
<div id="contextMenu" class="context-menu">
    <div class="context-menu-item" data-action="preview">
        <i class="fas fa-eye"></i> 预览
    </div>
    <div class="context-menu-item" data-action="download">
        <i class="fas fa-download"></i> 下载
    </div>
</div>

<!-- 下载模态框 -->
<div class="modal fade" id="downloadModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">下载资源</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="mb-3">您即将下载：<strong id="softwareName" class="text-primary"></strong></p>
                <div class="row g-3 mb-2">
                    <div class="col-md-6">
                        <div class="bg-light rounded p-2">
                            <label class="form-label text-sm text-muted">文件大小：</label>
                            <span id="fileSize" class="badge bg-info"></span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="bg-light rounded p-2">
                            <label class="form-label text-sm text-muted">文件类型：</label>
                            <span id="fileType" class="badge bg-secondary"></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="bg-light rounded p-2">
                            <label class="form-label text-sm text-muted">文件ID：</label>
                            <span id="fileId" class="badge bg-light text-dark"></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <a id="downloadLink" href="#" class="btn btn-primary">
                    <i class="fas fa-download me-1"></i> 立即下载
                </a>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/js/jQuery.js}"></script>
<script th:src="@{/js/bootstrap.js}"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        let baseUrl;

        // --- 初始化 server IP（保持你原有逻辑） ---
        async function getServerIP() {
            try {
                const response = await fetch('/getIp');
                if (!response.ok) throw new Error('HTTP ' + response.status);
                return (await response.text()).trim();
            } catch (e) {
                console.warn('getIp failed, use hostname', e);
                return window.location.hostname;
            }
        }

        (async function init() {
            try {
                const ip = await getServerIP();
                baseUrl = 'http://' + ip;
            } catch (e) {
                baseUrl = window.location.origin;
            }
        })();

        // ----- 工具函数 -----
        function formatFileSize(bytes) {
            if (!bytes || bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 读取URL参数
        function readUrlParams() {
            const urlParams = new URLSearchParams(window.location.search);
            return {
                query: urlParams.get('query'),
                level1Id: urlParams.get('level1Id'),
                level2Id: urlParams.get('level2Id')
            };
        }

        // 文件大小格式化
        document.querySelectorAll('.file-size').forEach(item => {
            const bytes = parseInt(item.getAttribute('data-size'));
            item.textContent = formatFileSize(bytes);
        });

        // 导航栏滚动效果
        $(window).scroll(function () {
            if ($(this).scrollTop() > 50) {
                $('.navbar').addClass('scrolled');
            } else {
                $('.navbar').removeClass('scrolled');
            }
        });

        // 分类折叠功能
        function initCategoryCollapse() {
            // 获取当前分类ID
            const urlParams = new URLSearchParams(window.location.search);
            const currentLevel1Id = urlParams.get('level1Id');
            const currentLevel2Id = urlParams.get('level2Id');

            // 默认展开当前选中的一级分类
            if (currentLevel1Id) {
                const currentLevel1Item = document.querySelector(`.categoryLevel1-item[data-level1-id="${currentLevel1Id}"]`);
                if (currentLevel1Item) {
                    toggleCategory(currentLevel1Item);
                }
            }

            // 为所有一级分类项添加点击事件
            document.querySelectorAll('.categoryLevel1-item').forEach(item => {
                item.addEventListener('click', function (e) {
                    e.preventDefault();
                    toggleCategory(this);
                });
            });
        }

        function toggleCategory(categoryElement) {
            const level2Container = categoryElement.nextElementSibling;

            if (level2Container && level2Container.classList.contains('level2-container')) {
                if (level2Container.classList.contains('expanded')) {
                    // 折叠
                    level2Container.classList.remove('expanded');
                    categoryElement.classList.remove('expanded');
                } else {
                    // 展开
                    level2Container.classList.add('expanded');
                    categoryElement.classList.add('expanded');
                }
            }
        }

        // 文件hover显示全名功能
        const tooltipElement = document.createElement('div');
        tooltipElement.className = 'software-tooltip';
        document.body.appendChild(tooltipElement);

        document.querySelectorAll('.file-card').forEach(item => {
            item.addEventListener('mouseenter', function (e) {
                const fullName = this.getAttribute('data-name');
                const nameElement = this.querySelector('.file-title');

                if (nameElement.scrollWidth > nameElement.clientWidth) {
                    tooltipElement.textContent = fullName;
                    const itemRect = this.getBoundingClientRect();
                    const tooltipRect = tooltipElement.getBoundingClientRect();

                    let left = itemRect.left + (itemRect.width - tooltipRect.width) / 2;
                    const top = itemRect.bottom + 8;

                    if (left < 10) left = 10;
                    const maxLeft = window.innerWidth - tooltipRect.width - 10;
                    if (left > maxLeft) left = maxLeft;

                    tooltipElement.style.left = `${left}px`;
                    tooltipElement.style.top = `${top}px`;

                    setTimeout(() => {
                        tooltipElement.style.opacity = '1';
                    }, 100);
                }
            });

            item.addEventListener('mouseleave', function () {
                tooltipElement.style.opacity = '0';
            });

            item.addEventListener('mousemove', function (e) {
                if (tooltipElement.style.opacity === '1') {
                    const itemRect = this.getBoundingClientRect();
                    const tooltipRect = tooltipElement.getBoundingClientRect();

                    let left = itemRect.left + (itemRect.width - tooltipRect.width) / 2;
                    const top = itemRect.bottom + 8;

                    if (left < 10) left = 10;
                    const maxLeft = window.innerWidth - tooltipRect.width - 10;
                    if (left > maxLeft) left = maxLeft;

                    tooltipElement.style.left = `${left}px`;
                    tooltipElement.style.top = `${top}px`;
                }
            });
        });

        window.addEventListener('scroll', function () {
            if (tooltipElement.style.opacity === '1') {
                tooltipElement.style.opacity = '0';
            }
        });

        // 右键菜单与模态框功能
        const contextMenu = document.getElementById('contextMenu');
        const downloadModal = new bootstrap.Modal(document.getElementById('downloadModal'));
        let selectedSoftwareId = null;
        let selectedSoftwareName = null;
        let selectedFileSize = null;
        let selectedFileType = null;
        let selectedFileUUIDName = null;

        // 为文件卡片绑定事件
        document.querySelectorAll('.file-card').forEach(item => {
            // 右键菜单
            item.addEventListener('contextmenu', function (e) {
                e.preventDefault();
                selectedSoftwareId = this.getAttribute('data-id');
                selectedSoftwareName = this.getAttribute('data-name');
                selectedFileSize = this.getAttribute('data-size');
                selectedFileType = this.getAttribute('data-type');
                selectedFileUUIDName = this.getAttribute('data-uuid-name');

                const menuWidth = contextMenu.offsetWidth;
                const menuHeight = contextMenu.offsetHeight;
                const windowWidth = window.innerWidth;
                const windowHeight = window.innerHeight;

                let left = e.pageX;
                let top = e.pageY;

                if (left + menuWidth > windowWidth) left = e.pageX - menuWidth;
                if (top + menuHeight > windowHeight) top = e.pageY - menuHeight;

                contextMenu.style.display = 'block';
                contextMenu.style.left = left + 'px';
                contextMenu.style.top = top + 'px';
            });

            // 点击显示下载模态框
            item.addEventListener('click', function () {
                selectedSoftwareId = this.getAttribute('data-id');
                selectedSoftwareName = this.getAttribute('data-name');
                selectedFileSize = this.getAttribute('data-size');
                selectedFileType = this.getAttribute('data-type');
                selectedFileUUIDName = this.getAttribute('data-uuid-name');

                document.getElementById('softwareName').textContent = selectedSoftwareName;
                document.getElementById('fileSize').textContent = formatFileSize(selectedFileSize);
                document.getElementById('fileType').textContent = selectedFileType.toUpperCase();
                document.getElementById('fileId').textContent = selectedSoftwareId;

                document.getElementById('downloadLink').href = 'api/file/download?fileId=' + selectedSoftwareId;
                downloadModal.show();
            });
        });

        // 右键菜单选项点击
        document.querySelectorAll('.context-menu-item').forEach(item => {
            item.addEventListener('click', function () {
                const action = this.getAttribute('data-action');
                contextMenu.style.display = 'none';

                if (action === 'download') {
                    document.getElementById('softwareName').textContent = selectedSoftwareName;
                    document.getElementById('fileSize').textContent = formatFileSize(selectedFileSize);
                    document.getElementById('fileType').textContent = selectedFileType.toUpperCase();
                    document.getElementById('fileId').textContent = selectedSoftwareId;

                    document.getElementById('downloadLink').href = 'api/file/download?fileId=' + selectedSoftwareId;
                    downloadModal.show();
                } else if (action === 'preview') {
                    const previewUrl = baseUrl + `/onlinePreview?fileId=${selectedSoftwareId}`;
                    window.open(previewUrl, '_blank', 'width=1000,height=800,top=100,left=100');
                }
            });
        });

        // 点击页面其他区域隐藏右键菜单
        document.addEventListener('click', function () {
            contextMenu.style.display = 'none';
        });

        // 阻止右键菜单区域点击时冒泡
        contextMenu.addEventListener('click', function (e) {
            e.stopPropagation();
        });

        // 窗口大小变化时隐藏右键菜单
        window.addEventListener('resize', function () {
            if (contextMenu.style.display === 'block') {
                contextMenu.style.display = 'none';
            }
        });

        // 模态框关闭时清空选中状态
        document.getElementById('downloadModal').addEventListener('hidden.bs.modal', function () {
            selectedSoftwareId = null;
            selectedSoftwareName = null;
            selectedFileSize = null;
            selectedFileType = null;
            selectedFileUUIDName = null;
        });

        // 搜索功能 - 修复参数传递
        document.getElementById('searchForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const query = document.getElementById('searchInput').value.trim();
            const urlParams = new URLSearchParams(window.location.search);
            const currentCategoryId = urlParams.get('categoryId');

            const params = new URLSearchParams();
            if (query) {
                params.append('query', query);
            }
            if (currentCategoryId && currentCategoryId !== 'null') {
                params.append('categoryId', currentCategoryId);
            }

            window.location.href = '?' + params.toString();
        });

        // 分类点击处理（结合搜索）- 修复参数传递
        document.querySelectorAll('.categoryLevel2-item-nested').forEach(el => {
            el.addEventListener('click', function (e) {
                e.preventDefault();
                const level1Id = this.getAttribute('data-level1-id');
                const level2Id = this.getAttribute('data-level2-id');
                const query = document.getElementById('searchInput') ? document.getElementById('searchInput').value.trim() : '';
                navigateWithParams({query: query || null, level1Id: level1Id || null, level2Id: level2Id || null});
            });
        });

        // 帮助函数：构建 URL 查询参数并导航
        function navigateWithParams(paramsObj) {
            const params = new URLSearchParams();
            if (paramsObj.query) params.set('query', paramsObj.query);
            if (paramsObj.level1Id) params.set('level1Id', paramsObj.level1Id);
            if (paramsObj.level2Id) params.set('level2Id', paramsObj.level2Id);
            window.location.href = '?' + params.toString();
        }

        // 搜索栏分类更新：保留 query、level1Id 和 level2Id 参数
        (function syncCategoryHref() {
            const cur = readUrlParams();
            document.querySelectorAll('.categoryLevel2-item-nested').forEach(el => {
                const lvl1 = el.getAttribute('data-level1-id');
                const lvl2 = el.getAttribute('data-level2-id');
                const params = new URLSearchParams();
                if (cur.query) params.set('query', cur.query);
                if (lvl1) params.set('level1Id', lvl1);
                if (lvl2) params.set('level2Id', lvl2);
                el.href = '?' + params.toString();
            });
        })();

        // 卡片动画
        setTimeout(() => {
            document.querySelectorAll('.file-card').forEach((card, index) => {
                setTimeout(() => {
                    card.style.opacity = '1';
                }, 100 * index);
            });
        }, 100);

        // 初始化分类折叠功能
        initCategoryCollapse();
    });
</script>
</body>
</html>